package com.space.school.controller;

import com.space.school.service.RegisterService;
import com.space.school.service.impl.RegisterServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "registerServlet", value = "/registerServlet")
public class RegisterServlet extends HttpServlet {
    RegisterService registerService = new RegisterServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("register.jsp").forward(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        boolean checkUsername = registerService.usernameExists(userName);
        boolean checkPassword = registerService.passwordCheck(passWord);
//        先检查
        if (checkUsername && checkPassword) {
            registerService.register(userName, passWord);
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        }else {
            if (!checkUsername) {
                req.setAttribute("message","您的账户已存在，请登录");
                req.getRequestDispatcher("register.jsp").forward(req, resp);
            }else if (!checkPassword) {
                req.setAttribute("message","密码必须是 6位大写,小写,数字都必须有,你的密码设置太简单了,请重新注册");
                req.getRequestDispatcher("register.jsp").forward(req, resp);
            }
        }
    }
}
